#!/usr/bin/env python
# -*- coding:utf-8 -*-
import collections
from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Count
from web import models

from datetime import datetime
from collections import defaultdict, OrderedDict
from django.db.models import Count
from django.utils.timezone import make_aware
from django.core.exceptions import ValidationError


def statistics(request, project_id):
    """ 统计页面"""

    return render(request, 'statistics.html')


def statistics_priority(request, project_id):
    """ 按照优先级生成饼图 """

    # 找到所有的问题，根据优先级分组，每个优先级的问题数量
    start = request.GET.get('start')
    end = request.GET.get('end')

    # 1.构造字典
    data_dict = collections.OrderedDict()
    for key, text in models.Issues.priority_choices:
        data_dict[key] = {'name': text, 'y': 0}

    # 2.去数据查询所有分组得到的数据量
    result = models.Issues.objects.filter(project_id=project_id, create_datetime__gte=start,
                                          create_datetime__lt=end).values('priority').annotate(ct=Count('id'))

    # 3.把分组得到的数据更新到data_dict中
    for item in result:
        data_dict[item['priority']]['y'] = item['ct']

    return JsonResponse({'status': True, 'data': list(data_dict.values())})


def statistics_project_user(request, project_id):
    """ 按照优先级生成饼图 """
    start = request.GET.get('start')
    end = request.GET.get('end')
    # 1. 预定义状态字典
    status_choices = models.Issues.status_choices
    #{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}
    status_dict = {status[0]: 0 for status in status_choices}
    print(status_dict)

    # 2. 获取所有成员及未指派进行初始化
    all_user_dict = OrderedDict()
    all_user_dict[None] = {
        'name': '未指派',
        'status': status_dict.copy()
    }

    # 添加项目创建者
    all_user_dict[request.tracer.project.creator.id] = {
        'name': request.tracer.project.creator.username,
        'status': status_dict.copy()
    }

    # 添加项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).select_related('user')
    for item in user_list:
        all_user_dict[item.user_id] = {
            'name': item.user.username,
            'status': status_dict.copy()
        }

    # 3. 批量获取问题并统计状态
    #<QuerySet [{'assign_id': 3, 'status': 1, 'count': 1}]>....
    issues = models.Issues.objects.filter(
        project_id=project_id,
        create_datetime__gte=start,
        create_datetime__lt=end
    ).values('assign_id', 'status').annotate(count=Count('id'))

    # 使用 defaultdict 统计状态
    #{3: defaultdict(<class 'int'>, {1: 1})})....
    status_count = defaultdict(lambda: defaultdict(int))
    for issue in issues:
        user_key = issue['assign_id'] if issue['assign_id'] else None
        status_count[user_key][issue['status']] += issue['count']
    # 4. 更新 all_user_dict 中的状态
    #([(None, {'name': '未指派', 'status': {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}}),
    # (3, {'name': 'lihaixia', 'status': {1: 1, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}}),
    # (4, {'name': 'lhx', 'status': {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}})])
    for user_key, status_data in status_count.items():
        for status, count in status_data.items():
            all_user_dict[user_key]['status'][status] = count
    # 5. 构造 categories 和 series
    #series = [{'name': '新建', 'data': [0, 3, 0]}, {'name': '处理中', 'data': [1, 0, 1]}, {'name': '已解决', 'data': [1, 1, 0]}]
    categories = [user_data['name'] for user_data in all_user_dict.values()]
    series = []
    for status_key, status_name in status_choices:
        status_data = {
            'name': status_name,
            'data': [user_data['status'][status_key] for user_data in all_user_dict.values()]
        }
        # 如果该状态没有数据，则不添加到 series 中
        if any(status_data['data']):
            series.append(status_data)
    # 6. 构造最终结果
    context = {
        'status': True,
        'data': {
            'categories': categories,
            'series': series
        }
    }
    return JsonResponse(context)
